package com.vallis.lotteryonline.filter;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.vallis.lotteryonline.annotation.JwtIgnore;
import com.vallis.lotteryonline.entity.Audience;
import com.vallis.lotteryonline.exception.CustomException;
import com.vallis.lotteryonline.util.Base64Util;
import com.vallis.lotteryonline.util.JwtTokenUtil;
import com.vallis.lotteryonline.util.Result;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

public class JwtInterceptor extends HandlerInterceptorAdapter {
    @Autowired
    private Audience audience;
    private static final Logger log = LoggerFactory.getLogger(JwtInterceptor.class);

    public static final Map<String, String> userMap = new HashMap<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    
    
        System.out.println("============拦截========"+request.getRequestURL());
    
        String header = request.getHeader("Access-Control-Allow-Origin");
        request.setAttribute("Access-Control-Allow-Origin","true");
      //  System.out.println(header);
    
        // 忽略带JwtIgnore注解的请求, 不做后续token认证校验
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            JwtIgnore jwtIgnore = handlerMethod.getMethodAnnotation(JwtIgnore.class);
            if (jwtIgnore != null) {
                return true;
            }
        }

        if (HttpMethod.OPTIONS.equals(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }

        // 获取请求头信息authorization信息
        final String authHeader = request.getHeader(JwtTokenUtil.AUTH_HEADER_KEY);
        //log.info("## authHeader= {}", authHeader);

        if (StringUtils.isBlank(authHeader) || !authHeader.startsWith(JwtTokenUtil.TOKEN_PREFIX)) {
            //        log.info("### 用户未登录，请先登录 ###");
            throw new CustomException(Result.error("用户未登录，请先登录"));
        }

        // 获取token
        final String token = authHeader.substring(7);

        if (audience == null) {
            BeanFactory factory = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
            audience = (Audience) factory.getBean("audience");
        }

        // 验证token是否有效--无效已做异常抛出，由全局异常处理后返回对应信息
        Claims claims = JwtTokenUtil.parseJWT(token, audience.getBase64Secret());
        String id = Base64Util.decode(claims.get("userId", String.class));
        userMap.put("id", id);
        return true;
    }
}
